import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Card,
  Table,
  Divider,
  Row,
  Col,
  Select,
  Button,
  Input,
  Tag,
  Checkbox,
  DatePicker,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { routerRedux } from 'dva/router';
import MyTreeLine from '../../components/_public/MyTreeLine';
import { getParamUrl, getMathJax, minHeight } from '../../utils/formatDataSource';

@connect(({ wrongs1, lesson1, loading }) => ({
  wrongs:wrongs1,
  lesson:lesson1,
  loading: loading.models.lesson,
}))
class WrongQuestion extends PureComponent {
  state = {
    startTime: '',
    entTime: '',
    searchStem: '',
    tableTotal: 0,
    treeSelected: [],
    tableSelected: [],
    selectedStudents: [],
    treeList: [],
    lessonId: '',
  };

  componentDidMount() {
    const { dispatch, location: { search } } = this.props;
    const params = getParamUrl(search);
    this.setState({ lessonId: params.lessonId });
    dispatch({
      type: 'wrongs/questions',
      payload: params,
    });
  }
  serverRequest = other => {
    const { dispatch, location: { search } } = this.props;
    const params = getParamUrl(search);
    dispatch({
      type: 'wrongs/questions',
      payload: {
        ...params,
        ...other,
      },
    });
  };
  getColumns = () => {
    return [
      {
        title: '题目名称',
        dataIndex: 'stem',
        key: 'stem',
        width: '70%',
        render: record => {
          return <span>{getMathJax(record)}</span>;
        },
      },
      {
        title: '类型',
        dataIndex: 'questionType',
        key: 'age',
        width: '15%',
      },
      {
        title: '正确率',
        dataIndex: 'rightRate',
        key: 'rightRate',
        width: '15%',
      },
    ];
  };

  getDatasource = () => {
    const { questionInfo } = this.props.wrongs;

    const questions = questionInfo.data !== undefined ? questionInfo.data.questions : [];

    const total = questionInfo.data !== undefined ? questionInfo.data.total : 0;

    this.setState({
      tableTotal: total,
    });

    return questions;
  };

  handleCheck = (treeSelected, totalKeys) => {
    this.setState({
      treeSelected: treeSelected,
    });
  };

  handleSelect = value => {
    let params = {};
    if (value !== '0') {
      params.questionType = value;
    }
    this.serverRequest(params);
  };

  handleStudentSelect = e => {
    console.log(e);
    this.setState({
      selectedStudents: [...e],
    });
  };

  getSutdents = () => {
    const { questionInfo } = this.props.wrongs;

    const data = questionInfo.students != undefined ? questionInfo.students : [];

    return data.map(d => {
      return {
        label: <Tag color={d.disabled ? '#87d068' : '#2db7f5'}>{d.label}</Tag>,
        value: d.value,
        disabled: d.disabled,
      };
    });
  };

  handleInput = e => {
    this.setState({
      searchStem: e.target.value,
    });
  };

  searchByStem = param => {
    const { selectedStudents } = this.state;

    if (this.state.searchStem !== '') {
      param.stem = this.state.searchStem;
    }

    if (selectedStudents.length !== 0) {
      param.studentIds = selectedStudents.join(',');
    }

    this.serverRequest(param);
  };

  submitTable = () => {
    const { dispatch, location: { search } } = this.props;

    const { tableSelected, selectedStudents } = this.state;

    const params = getParamUrl(search);

    const questionIds = tableSelected.join(',');

    const studentIds = selectedStudents.join(',');

    dispatch({
      type: 'wrongs/saveError',
      payload: {
        ...params,
        questionIds,
        studentIds,
      },
    });

    console.log(tableSelected, selectedStudents);
  };

  timeChange = (date, dateString) => {
    this.setState({
      startTime: dateString[0],
      endTime: dateString[1],
    });
  };

  searchTrees = () => {
    // todo 根据选择的时间段 去查询改时间段，对应的课程所设计到的知识树
    const { startTime, endTime } = this.state;

    const { dispatch } = this.props;

    dispatch({
      type: 'wrongs/searchTree',
      payload: {
        startTime,
        endTime,
      },
    });
  };

  handleTablePage = value => {
    const { current: page, pageSize } = value;

    this.searchByStem({ page, pageSize });
  };

  render() {
    const { RangePicker } = DatePicker;

    const Option = Select.Option;

    const CheckboxGroup = Checkbox.Group;

    const { treeList = [] } = this.props.wrongs;

    const { tableSelected } = this.state;

    console.log(treeList);

    const rowSelection = {
      selectedRowKeys: tableSelected,
      onChange: (tableSelected, selectedRows) => {
        console.log(`tableSelected: ${tableSelected}`, 'selectedRows: ', selectedRows);

        this.setState({
          tableSelected: [...tableSelected],
        });
      },
      getCheckboxProps: record => ({
        // disabled: record.key === '1', // Column configuration not to be checked
        // checked: record.key === '1',
      }),
    };

    return (
      <PageHeaderLayout>
        <Col span={8}>
          <Card bordered={true} style={{ minHeight: minHeight }}>
            <div>
              <Row>
                <Col span={18}>
                  <RangePicker onChange={this.timeChange} />
                </Col>
                <Col span={6}>
                  {' '}
                  <Button onClick={() => this.searchTrees()} type="primary">
                    查询
                  </Button>{' '}
                </Col>
              </Row>
            </div>
            <div>
              <MyTreeLine dataSource={treeList} />
            </div>
          </Card>
        </Col>
        <Col span={16}>
          <Card bordered={false}>
            <Row type="flex" align="middle">
              <Col span={20}>
                <CheckboxGroup options={this.getSutdents()} onChange={this.handleStudentSelect} />
              </Col>
              <Col span={4} style={{ textAlign: 'right' }}>
                <Button type="primary" size="small" onClick={() => this.searchByStem({})}>
                  去配置
                </Button>&nbsp;&nbsp;
                <Button
                  type="primary"
                  size="small"
                  onClick={() =>
                    this.props.dispatch(
                      routerRedux.push(`/lesson/3/lesson-info?lessonId=${this.state.lessonId}`)
                    )
                  }
                >
                  返回
                </Button>
              </Col>
            </Row>
            <Divider />
            <div span={24}>
              <Input
                placeholder="请输入题目"
                style={{ width: '300px', marginRight: '20px' }}
                value={this.state.searchStem}
                onChange={this.handleInput}
              />
              <Button type="primary" onClick={() => this.searchByStem({})}>
                搜索
              </Button>
              <span push={5}>
                <Select defaultValue="0" style={{ width: 120 }} onChange={this.handleSelect}>
                  <Option value="0">全部</Option>
                  <Option value="1">选择题</Option>
                  <Option value="2">填空题</Option>
                  <Option value="3">简答题</Option>
                </Select>
              </span>
            </div>
            <Table
              dataSource={this.getDatasource()}
              columns={this.getColumns()}
              rowSelection={rowSelection}
              onChange={this.handleTablePage}
              pagination={{ total: this.state.tableTotal, defaultPageSize: 10 }}
            />
          </Card>
          <Card bordered={false} style={{ textAlign: 'right' }}>
            <Button
              type="primary"
              onClick={this.submitTable}
              disabled={
                this.state.selectedStudents.length === 0 || this.state.tableSelected.length === 0
              }
            >
              确认生成
            </Button>
          </Card>
        </Col>
      </PageHeaderLayout>
    );
  }
}

export default WrongQuestion;
